<template>
  <el-dialog
    v-model="dialogVisible"
    title="更新服务提供商价格"
    width="400px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules">
      <el-form-item label="价格" prop="costPrice">
        <el-input-number v-model="form.costPrice" :min="0" class="!w-[100%]" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleConfirm"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import {
  updatePricesBatch,
  updateServicePrice
} from "@/api/adminThirdPartyApi";
import { message } from "@/utils/message";

const dialogVisible = ref(false);
const formList = ref([]);
const emits = defineEmits(["refresh"]);
const form = ref({
  costPrice: 0
});

// 基础校验规则
const rules = {
  costPrice: [
    { required: true, message: "请输入价格", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("价格必须大于0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
  serviceForm.value?.clearValidate();
};
const submitLoading = ref(false);

const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        submitLoading.value = true;
        const paramsList = formList.value.map(
          ({ standardCode, apiProvider }) => {
            return {
              standardCode,
              provider: apiProvider,
              costPrice: form.value.costPrice
            };
          }
        );
        if (paramsList.length === 1) {
          await updateServicePrice(paramsList[0]);
        } else {
          await updatePricesBatch(paramsList);
        }
        message("更新成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      } finally {
        submitLoading.value = false;
      }
    } else {
      console.log("表单校验失败");
      return false;
    }
  });
};
const open = list => {
  formList.value = list;
  if (list.length === 1) {
    form.value.costPrice = list[0].costScore;
  }
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
